<!-- 受试者 -->
<template>
  <a-card :bordered="false">
    <s-table
      ref="table"
      rowKey="id"
      :columns="$auth('PROJECT.PROJECT_PATIENT_LIST') ? columns:[]"
      :data="loadData"
      :scroll="{x: 'max-content'}"
    >
      <template slot="title">
        <!-- <a-descriptions :title="$t('all.autotext433')"></a-descriptions> -->
        <div class="table-page-search-wrappers">
          <!-- 筛选区域 -->
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="8" :sm="24">
                <a-form-item :label="$t('all.autotext357')">
                  <a-select v-model="queryParam.researchId" allowClear>
                    <a-select-option v-for="item in centerList" :value="item.id" :key="item.id">
                      {{ item.researchCenterNo }} - {{ item.orgName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item :label="$t('all.autotext830')">
                  <a-select v-model="queryParam.ptsStatus" allowClear>
                    <a-select-option v-for="(item, index) in $const.RELATION_STATUS" :value="item.value" :key="index">
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="activeQuery">{{ $t('all.autotext30') }}</a-button>
                  <a-button style="margin-left: 8px" @click="resetParams">{{ $t('all.autotext340') }}</a-button>
                  <a-button
                    style="margin-left: 8px"
                    icon="export"
                    @click="clickExport"
                    v-if="$auth('PROJECT.PROJECT_PATIENT_EXPORT')"
                    :disabled="$store.state.user.project.status === 3"
                  >{{ $t('all.autotext1014') }}</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
          <div>
            <a-space>
              <a-button
                type="primary"
                icon="plus"
                v-if="$auth('PROJECT.PROJECT_PATIENT_INVITE')"
                @click="addInvitation()"
                :disabled="$store.state.user.project.status === 3"
              >
                {{ $t('all.autotext1462') }}
              </a-button>
              <a-button v-if="$auth('PROJECT.PROJECT_PATIENT_INVITE')" @click="downloadMode">
                {{ $t('all.autotext626') }}
              </a-button>
              <a-upload
                v-if="$auth('PROJECT.PROJECT_PATIENT_INVITE')"
                accept=".xlsx"
                name="file"
                :showUploadList="false"
                :customRequest="handleUpload"
              >
                <a-button icon="upload">{{ $t('subject.autotext22') }}</a-button>
              </a-upload>
            </a-space>
          </div>
        </div>
      </template>
      <template slot="orgName" slot-scope="text, record">
        <span>{{ record.researchCenterNo + '-' + record.orgName }} </span>
      </template>
      <template slot="ptsStatus" slot-scope="text, record">
        <span>{{ record.ptsStatus | enumValueByKey($const.RELATION_STATUS) }} </span>
      </template>
      <template slot="authorizationAppletType" slot-scope="text">
        <span>{{ text | enumValueByKey($const.AUTHORIZATION_TYPE, 'desc', '-') }} </span>
      </template>
      <template slot="payAmount" slot-scope="text">
        <span>{{ text ? `￥${text}` : '￥0.00' }} </span>
      </template>
      <template slot="applyAmount" slot-scope="text">
        <span>{{ text ? `￥${text}` : '￥0.00' }} </span>
      </template>
      <template slot="guardianId" slot-scope="text, record">
        <span>{{ record.guardianId ? $t('all.autotext263.2') : $t('all.autotext263') }}  <span
          :style="{ color: record.guardianProveFileUrl ? '#1890ff' : '#666'}"
          :title="record.guardianProveFileUrl ? $t('subject.autotext34') : $t('subject.autotext33')"
        ><a-icon type="file-text"  />
        </span></span>
      </template>
      <template slot="status" slot-scope="text, record">
        <a-space size="large">
          <span>
            {{ $t('all.autotext446') }}：
            <a-popover
              :title="$t('all.autotext1478')"
              v-if="record.authStatus && $auth('PROJECT.PROJECT_PATIENT_EDIT')"
            >
              <template slot="content">
                <a-space>
                  <a-popconfirm
                    :title="$t('all.autotext98')"
                    :ok-text="$t('all.autotext792')"
                    :cancel-text="$t('all.autotext975')"
                    @confirm="actionCalcel(record, 1)"
                  >
                    <a-button class="btn-border" size="small" v-if="record.authStatus == 4">
                      {{ $t('all.autotext603') }}
                    </a-button>
                  </a-popconfirm>
                  <a-popconfirm
                    :title="record.authStatus === $const.RELATION_WX.INVITE.value ? $t('all.autotext906') : $t('all.autotext788')"
                    @confirm="clickReinvite(record, 1)"
                  >
                    <a-button
                      class="btn-border"
                      size="small"
                      v-if="(record.authStatus == 5 || record.authStatus == 4 || record.authStatus == 2) && $auth('PROJECT.PROJECT_PATIENT_EDIT')"
                    >
                      {{ record.authStatus === 5 ? $t('all.autotext1470.1') : $t('all.autotext1470.2') }}
                    </a-button>
                  </a-popconfirm>
                  <a-popconfirm
                    :title="$t('all.autotext98')"
                    :ok-text="$t('all.autotext792')"
                    :cancel-text="$t('all.autotext975')"
                    @confirm="wxCalcel(record, 1)"
                  >
                    <a-button class="btn-border" size="small" v-if="record.authStatus == 1">
                      {{ $t('all.autotext1298') }}
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
              <span :style="record.authStatus | enumValueByKey($const.RELATION_WX, 'style')">{{ record.authStatus | enumValueByKey($const.RELATION_WX) }} </span>
            </a-popover>
            <span
              v-else
              :style="record.authStatus | enumValueByKey($const.RELATION_WX, 'style')"
            >{{ record.authStatus | enumValueByKey($const.RELATION_WX, 'desc', $t('all.autotext263')) }}
            </span>
          </span>
          <span>
            {{ $t('subject.autotext2') }}：
            <a-popover
              :title="$t('all.autotext1478')"
              v-if="record.guardianAuthStatus && $auth('PROJECT.PROJECT_PATIENT_EDIT')"
            >
              <template slot="content">
                <a-space>
                  <a-popconfirm :title="$t('all.autotext98')" @confirm="actionCalcel(record, 2)">
                    <a-button class="btn-border" size="small" v-if="record.guardianAuthStatus == 4">
                      {{ $t('all.autotext603') }}
                    </a-button>
                  </a-popconfirm>
                  <a-popconfirm
                    :title="record.guardianAuthStatus === $const.RELATION_WX.INVITE.value ? $t('all.autotext906') : $t('all.autotext788')"
                    @confirm="clickReinvite(record, 2)"
                  >
                    <a-button
                      class="btn-border"
                      size="small"
                      v-if="(record.guardianAuthStatus == 5 || record.guardianAuthStatus == 4 || record.guardianAuthStatus == 2) && $auth('PROJECT.PROJECT_PATIENT_EDIT')"
                    >
                      {{ record.guardianAuthStatus === 5 ? $t('all.autotext1470.1') : $t('all.autotext1470.2') }}
                    </a-button>
                  </a-popconfirm>
                  <a-popconfirm :title="$t('all.autotext98')" @confirm="wxCalcel(record, 2)">
                    <a-button class="btn-border" size="small" v-if="record.guardianAuthStatus == 1">
                      {{ $t('all.autotext1298') }}
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
              <span :style="record.guardianAuthStatus | enumValueByKey($const.RELATION_WX, 'style')">{{ record.guardianAuthStatus | enumValueByKey($const.RELATION_WX, 'desc', $t('all.autotext263')) }} </span>
            </a-popover>
            <span
              v-else
              :style="record.guardianAuthStatus | enumValueByKey($const.RELATION_WX, 'style')"
            >{{ record.guardianAuthStatus | enumValueByKey($const.RELATION_WX, 'desc', $t('all.autotext263')) }}
            </span>
          </span>
        </a-space>
      </template>
      <template slot="operation" slot-scope="text, record" v-if="$store.state.user.project.status !== 3">
        <template v-if="!centerClosed(record)">
          <a
            style="margin-right: 10px"
            v-if="($auth('PROJECT.PROJECT_PATIENT_DETAIL') && !$auth('PROJECT.PROJECT_PATIENT_EDIT')) || record.ptsStatus === 6"
            @click="acticeView(record, 0)"
          >{{ $t('all.autotext568') }}</a>
          <a
            style="margin-right: 10px"
            v-if="$auth('PROJECT.PROJECT_PATIENT_EDIT') && record.ptsStatus !== 6"
            @click="acticeView(record, 1)"
          >{{ $t('all.autotext919') }}</a>
        </template>
      </template>
    </s-table>
    <!-- 添加受试者 -->
    <AddSubject ref="addSubjectRef" @handleSuccess="$refs.table.refresh(true)"/>
    <!-- 查看弹窗 -->
    <ViewModal
      :visible="viewVisible"
      @close="closeViewModal"
      :uId="uId"
      :isEdit="isEdit"
      ref="viewModalRef"
    />
  </a-card>
</template>

<script>
import { list, delPts, canPts, getSubjectExport, reinviteSubject, exportTemplate, batchImportPts, anewInviteGuardian, delGuardian, updateGuardianUserAuthorizeType } from '@/api/overview/subject'
import { getContractCenter } from '@/api/overview/member.js'
// import AddSubject from './addSubjectModal.vue'
import ViewModal from './subject/viewModal.vue' // 查看页面
import AddSubject from './addSubject'
import { exportExcel } from '@/utils/util'
import { buildPaginationObj } from '@/components/Table'
import { i18nRender } from '../../../../../locales'

export default {
  name: 'Subject',
  components: {
    AddSubject,
    ViewModal
  },
  data () {
    return {
      columns: [], // CRC和其他的角色看到的columns不一样
      visible: false,
      viewVisible: false,
      centerList: [],
      uId: '',
      queryParam: {
        proId: ''
      },
      loadData: parameter => {
        if (this.$auth('PROJECT.PROJECT_PATIENT_LIST')) {
          return list(Object.assign(parameter, this.queryParam)).then(res => {
            return res
          })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      isEdit: 0 // 0查看/1编辑受试者
    }
  },
  created () {
    const columnsOther = [
      {
        title: i18nRender('all.autotext949'),
        dataIndex: 'orgName',
        scopedSlots: { customRender: 'orgName' }
      },
      {
        title: i18nRender('all.autotext1357'),
        dataIndex: 'ptsNo'
      },
      {
        title: i18nRender('all.autotext830'),
        dataIndex: 'ptsStatus',
        scopedSlots: { customRender: 'ptsStatus' }
      },
      {
        title: i18nRender('all.autotext492'),
        dataIndex: 'userName'
      }
    ]
    const columnsCrcVisible = [
      {
        title: i18nRender('all.autotext949'),
        dataIndex: 'orgName',
        scopedSlots: { customRender: 'orgName' }
      },
      {
        title: i18nRender('all.autotext1357'),
        dataIndex: 'ptsNo'
      },
      // {
      //   title: '姓名缩写',
      //   dataIndex: 'ptsName',
      //   scopedSlots: { customRender: 'ptsName' }
      // },
      {
        title: i18nRender('all.autotext830'),
        dataIndex: 'ptsStatus',
        scopedSlots: { customRender: 'ptsStatus' }
      },
      {
        title: i18nRender('subject.autotext47'),
        dataIndex: 'authorizationAppletType',
        scopedSlots: { customRender: 'authorizationAppletType' }
      },
      {
        title: i18nRender('all.autotext1351'),
        dataIndex: 'payAmount',
        scopedSlots: { customRender: 'payAmount' }
      },
      {
        title: i18nRender('all.autotext589'),
        dataIndex: 'applyAmount',
        scopedSlots: { customRender: 'applyAmount' }
      },
      {
        title: i18nRender('subject.autotext2'),
        dataIndex: 'guardianId',
        scopedSlots: { customRender: 'guardianId' }
      },
      {
        // 审批状态 1：接受 2：拒绝 3：待处理 4：待加入 5: 待邀请
        title: i18nRender('all.autotext1384'),
        dataIndex: 'status',
        width: 280,
        scopedSlots: { customRender: 'status' }
      },
      {
        title: i18nRender('all.autotext187'),
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' },
        fixed: 'right'
      }
    ]
    const columnsCrcInVisible = [
      {
        title: i18nRender('all.autotext949'),
        dataIndex: 'orgName',
        scopedSlots: { customRender: 'orgName' }
      },
      {
        title: i18nRender('all.autotext1357'),
        dataIndex: 'ptsNo'
      },
      // {
      //   title: '姓名缩写',
      //   dataIndex: 'ptsName',
      //   scopedSlots: { customRender: 'ptsName' }
      // },
      {
        title: i18nRender('all.autotext830'),
        dataIndex: 'ptsStatus',
        scopedSlots: { customRender: 'ptsStatus' }
      },
      {
        title: i18nRender('subject.autotext2'),
        dataIndex: 'guardianId',
        scopedSlots: { customRender: 'guardianId' }
      },
      {
        title: i18nRender('all.autotext187'),
        dataIndex: 'operation',
        scopedSlots: { customRender: 'operation' },
        fixed: 'right'
      }
    ]
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.queryParam.proId = parseInt(pd)
    }
    // 如果有操作权限
    if (this.$auth('PROJECT.PROJECT_PATIENT_DETAIL') || this.$auth('PROJECT.PROJECT_PATIENT_EDIT')) {
      this.columns = this.$options.filters.isPtsVisible() ? columnsCrcVisible : columnsCrcInVisible
    } else {
      this.columns = columnsOther
    }
    // 保留上面的权限判断不删除，加下面一行覆盖掉，因为需求不明确，不知道后面要不要改回来😭
    this.columns = columnsCrcVisible

    this.getCenterList()
  },
  filters: {
    filtersState (val) {
      if (val === 1) {
        return i18nRender('all.autotext836')
      } else if (val === 2) {
        return i18nRender('all.autotext680')
      } else if (val === 3) {
        return i18nRender('all.autotext978')
      } else if (val === 4) {
        return i18nRender('all.autotext110')
      } else if (val === 5) {
        return i18nRender('all.autotext985')
      } else if (val === 6) {
        return i18nRender('all.autotext86')
      } else if (val === 7) {
        return i18nRender('all.autotext1109')
      } else if (val === 8) {
        return i18nRender('all.autotext691')
      } else if (val === 9) {
        return i18nRender('all.autotext1163')
      }
    },
    filterGender (val) {
      if (val === -1) {
        return i18nRender('all.autotext1048')
      } else if (val === 0) {
        return i18nRender('all.autotext1218')
      } else if (val === 1) {
        return i18nRender('all.autotext1007')
      }
    }
  },
  methods: {
    // 中心下拉列表
    getCenterList () {
      getContractCenter({ proId: this.queryParam.proId, deleted: 0 }).then(res => {
        this.centerList = res.content
      })
    },
    // 查询事件
    activeQuery () {
      this.$refs.table.refresh(true)
    },
    // 邀请
    addInvitation () {
      // this.visible = true
      this.$refs.addSubjectRef.open()
    },
    // 清空params
    resetParams () {
      this.queryParam = {
        proId: this.queryParam.proId
      }
      this.$refs.table.refresh(true)
    },
    // 中心关闭
    centerClosed ({ active }) {
      return +active === 2
    },
    // 打开查看弹窗
    acticeView (item, val) {
      this.viewSubject()
      this.uId = item.id
      this.viewVisible = true
      this.isEdit = val
    },
    // 邀请
    async clickReinvite (item, type) {
      if (type === 1) {
        await reinviteSubject({
          id: item.id,
          ptsNo: item.ptsNo,
          proId: item.proId,
          status: item.authStatus
        })
      } else {
        await anewInviteGuardian({
          proId: item.proId,
          guardianId: item.guardianId,
          status: item.guardianAuthStatus
        })
      }
      this.$message.success(this.$t('all.autotext1511'))
      this.$refs.table.refresh(true)
    },
    // 取消关联邀请
    async actionCalcel (item, type) {
      try {
        if (type === 1) {
          await delPts({ id: item.id })
        } else {
          await delGuardian({ guardianId: item.guardianId })
        }
        this.$message.success(this.$t('all.autotext470'))
        this.$refs.table.refresh(true)
      } catch (err) {
        this.$refs.table.refresh(true)
      }
    },
    // 取消关联
    async wxCalcel (item, type) {
      if (type === 1) {
        await canPts({ id: item.id })
      } else {
        await updateGuardianUserAuthorizeType({ guardianId: item.guardianId })
      }
      this.$message.success(this.$t('all.autotext470'))
      this.$refs.table.refresh(true)
    },
    // 关闭弹窗
    closeViewModal () {
      this.viewVisible = false
      this.$refs.table.refresh(true)
    },
    clickExport () {
      getSubjectExport({ proId: this.queryParam.proId, researchId: this.queryParam.researchId, ptsStatus: this.queryParam.ptsStatus })
        .then(res => {
          exportExcel(i18nRender('all.autotext446'), res)
        })
        .catch(() => {})
    },
    downloadMode () {
      exportTemplate({ proId: this.queryParam.proId }).then(res => {
        this.$message.success(this.$t('all.autotext638'))
        exportExcel(this.$t('all.autotext66'), res)
      })
    },
    // 上传文件end
    async handleUpload ({ file }) {
      const params = new FormData()
      params.append('proId', this.queryParam.proId)
      params.append('file', file)
      await batchImportPts(params)
      this.$message.success(i18nRender('all.autotext470'))
      this.$refs.table.refresh(true)
    },
    // 查看受试者详情埋点
    viewSubject () {}
  }
}
</script>
<style scoped lang="less">
.btn-border {
  border: 1px solid #1890ff;
  color: #1890ff;
  font-size: 12px;
}
</style>
